/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.cells.editors;

import cn.ac.nercis.pes.common.constant.common.AssetConstants;
import cn.ac.nercis.pes.community.support.controls.cells.editors.base.EditorNodeBuilder;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.scene.control.CheckBox;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Region;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 开关类型单元格编辑器
 * @author zpy
 * @version 1.0.0
 */
public class SwitchEditorBuilder implements EditorNodeBuilder<String> {

    protected CheckBox checkBox;

    @Override
    public void startEdit() {
        if(Objects.nonNull(checkBox)){
            Platform.runLater(()->checkBox.requestFocus());
        }
    }

    @Override
    public void cancelEdit() {

    }

    @Override
    public void updateItem(String aBoolean, boolean b) {
        if(Objects.nonNull(checkBox)){
            Platform.runLater(()->checkBox.requestFocus());
        }
    }

    @Override
    public Region createNode(String value, EventHandler<KeyEvent> eventHandler, ChangeListener<Boolean> changeListener) {
        checkBox = new CheckBox();
        checkBox.setSelected(StringUtils.equals(value, AssetConstants.USE_TAG));
        checkBox.setOnKeyPressed(eventHandler);
        checkBox.focusedProperty().addListener(changeListener);
        return checkBox;
    }

    @Override
    public void setValue(String value) {
        checkBox.setSelected(StringUtils.equals(value,AssetConstants.USE_TAG));
    }

    @Override
    public String getValue() {
        return checkBox.isSelected() ? AssetConstants.USE_TAG:AssetConstants.NOT_USE_TAG;
    }

    @Override
    public void validateValue() {

    }

    @Override
    public void nullEditorNode() {
        checkBox = null;
    }
}